package com.example.stringbufferlogger.Utils;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

public class CompareUtil {

    private final static String SEPARATOR = ",";

    private final static String CONNECTOR = "-";

    private final static String CHARSET = "GBK";

    /**
     * 根据指定范围截取字符串
     * @param res 待处理响应报文
     * @param rules 截取规则集合 1-10,20-30
     * @return
     */
    public static String dealSubString(String res,String rules){
        StringBuffer stringBuffer = new StringBuffer();
        try{
            byte[] resBytes = res.getBytes(CHARSET);
            String[] split = rules.split(SEPARATOR);
            for (String ruleString : split) {
                String[] rule = ruleString.split(CONNECTOR);
                String begin = rule[0];
                String end = rule[1];
                byte[] bytes = Arrays.copyOfRange(resBytes, Integer.valueOf(begin)-1, Integer.valueOf(end));
                String resString = new String(bytes, CHARSET);
                stringBuffer.append(resString);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return stringBuffer.toString();
    }

    /**
     * 根据指定范围去除字符串
     * @param res 待处理响应报文
     * @param rules 去除规则集合 1-10,20-30
     * @return
     */
    public static String dealRemoveString(String res,String rules){
        String[] splitRules = rules.split(SEPARATOR);
        StringBuffer bufferRules = new StringBuffer();
        try {
            bufferRules.append("1"+CONNECTOR);
            for (int i = 1; i <= splitRules.length; i++) {
                String[] split = splitRules[i-1].split(CONNECTOR);
                bufferRules.append((Integer.valueOf(split[0])-1) + SEPARATOR + (Integer.valueOf(split[1])+1) + CONNECTOR);
            }
                bufferRules.append(res.getBytes(CHARSET).length);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return dealSubString(res,bufferRules.toString());
    }

    public static void main(String[] args) throws Exception{
        System.out.println(dealSubString("123456测试abc", "1-2,3-8"));
    }

    /**
     * 截取日志中的保单号或团体保单号，需要支持循环参数截取，即报文中存在多条数据多个保单号
     * 如果存在多条格式为 首个保单号截取位置(1-15)|单条数据长度(50)|循环次数(10)
     * @param reqLog 请求日志
     * @param rule 规则
     * @return 保单号或团体保单号
     */
    public static String dealPolicyNo(String reqLog, String rule) {
        if (StringUtils.isBlank(reqLog) || StringUtils.isBlank(rule)) {
            throw new RuntimeException("dealPolicyNo方法所有入参不能为null或空字符串");
        }

        //删除请求报文交管请求头（前108位）
        reqLog = reqLog.substring(108);
        if (rule.contains("|")) {
            //一条日志存在多条保单号数据需要循环截取
            List<String> policyNoList = new ArrayList<>();
            String[] loopRule = rule.split("\\|");
            String subRule = loopRule[0];//首个保单号截取位置
            int dataLength = Integer.parseInt(loopRule[1]);//单条数据长度
            int loopCount = Integer.parseInt(loopRule[2]);//循环次数
            for (int i = 0; i < loopCount; i++) {
                String policyNo = dealSubString(reqLog, subRule);
                if (StringUtils.isBlank(policyNo)) {
                    // 循环截取保单号时，存在全是空格的情况，比如固定长度位100，十条数据，每条十位循环十次，
                    // 但是数据量只有5条，则后五条截取都是空格
                    // 如果为空，则视为后续保单号都是空格，退出循环
                    break;
                }
                policyNoList.add(policyNo);
                String[] subRuleSplit = subRule.split(CONNECTOR);
                int start = Integer.parseInt(subRuleSplit[0]) + dataLength;
                int end = Integer.parseInt(subRuleSplit[1]) + dataLength;
                subRule = start + CONNECTOR + end;
            }
            //存在多条数据保单号相同，做去重操作
            return policyNoList.stream().distinct().collect(Collectors.joining(SEPARATOR));
        } else {
            return dealSubString(reqLog, rule);
        }
    }

    /**
     * 获取文件路径
     * @param file
     * @param FilePaths
     * @return
     */
    public static List<String> getFilePath(File file, List<String> FilePaths){
        File[] files = file.listFiles();
        for (File f : files){
            if (f.isDirectory()){
                getFilePath(f,FilePaths);
            }else {
                FilePaths.add(f.getPath());
            }

        }
        return FilePaths;
    }

    /**
     * 大文件拆分
     *
     * @param inputFile, outputFile
     * @return void
     * @author wang****
     * @date: 2021/4/8 16:19
     */
    public static   List<String> largeFileSplit(String inputFile, String outputDir,String name) {
        ArrayList<String> paths = new ArrayList<>();
        int j = 0;
        try {
            File out = new File(outputDir);
            if (!out.exists()) {
                out.mkdirs();
            }
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream(new File(inputFile)));
            // 10M缓存
            BufferedReader in = new BufferedReader(new InputStreamReader(bis, "utf-8"), 10 * 1024 * 1024);
            int i = 0;
            while (in.ready()) {
                long startTime = System.currentTimeMillis();
                ++i;

                FileWriter fw = new FileWriter(outputDir + name+i + ".log");
                String path = outputDir + i + ".log";
                paths.add(path);
                String line = null;
                //500行一个文件拆分
                for (long lineCounter = 0; lineCounter < 500 && (line = in.readLine()) != null; ++lineCounter) {
                    fw.append(line + "\r");
                    ++j;
                }
                fw.flush();
                fw.close();
                long endTime = System.currentTimeMillis();
                System.out.println("第" + i + "个文件拆分成功，耗时：" + (float) (endTime - startTime) / 1000 + "秒");
            }
            in.close();
        } catch (IOException ex) {
            System.out.println("第" + j + "行数据拆分异常\r" + ex);
            ex.printStackTrace();
        }
        return paths;
    }
    public static  String getFormatDateStr(Date date, String format) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
        String dateStr = simpleDateFormat.format(date);
        return dateStr;
    }
    /**
     * 模拟返回值
     *
     * @date: 2021/4/8 16:19
     */
    public static String mockResult() {
        if (new Random().nextBoolean()) {
            return "0100105122023/11/0100:03:360000000                                                                 1  1  1  杨聚斌                                  11962/02/18201                                                            1     0101002                                                                                河南省平顶山市汝州市陵头镇陵头村6组                                       4675992019/06/30        nn9999/99/99                                                                                13071707778                                                                               9999999       CN 中国                                                                            杨聚斌                                                                                              ";
        } else {
            return "1200204B92023/11/0100:04:510000000                                                         2         1  0 15        0.00";
        }
    }

}
